const enterpriseVue = new Vue({
  el: '#app',
  data() {
    return {
      pickerOptions: pickerOptions,
      rules: {
        Article_Name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        Brand_SerialNumber: [{ required: true, message: '请选择商品品牌', trigger: 'change' }],
        Category_SerialNumber: [{ required: true, message: '请选择商品类别', trigger: 'change' }],
        Series_SerialNumber: [{ required: true, message: '请选择商品系列', trigger: 'change' }],
        Item_SerialNumber: [{ required: true, message: '请选择商品款型', trigger: 'change' }],
        Weight_Unit: [{ required: true, message: '请选择SKU单位', trigger: 'change' }],
        Unit_Price: [{ required: true, message: '请输入吊牌价', trigger: 'blur' }],
        Picture_URL: [{ required: true, message: '请输入图片地址', trigger: 'blur' }],
        App_ID: [{ required: true, message: '请输入App_ID', trigger: 'blur' }],
      },
      Specifications_Name: [{ required: true, message: '请输入规格', trigger: 'blur' }],
      Packing: [{ required: true, message: '请输入SKU数量', trigger: 'blur' }],
      PackingSize: [{ required: true, message: '请输入装箱尺寸', trigger: 'blur' }],
      OutsidePackingSize: [{ required: true, message: '请输入外箱尺寸', trigger: 'blur' }],
      Unit_Price: [{ required: true, message: '请输入零售价', trigger: 'blur' }],
      Net_Content: [{ required: true, message: '请输入净含量', trigger: 'blur' }],
      brand: [],
      category: [],
      series: [],
      item: [],
      unit: [],
      province:[],
      dealer: [],
      fileList: [],
      fileList1: [],
      fileList2: [],
      fileXlsx: [],
      dialogImageUrl: '',
      dialogVisible: false,
      dialogVisible1: false,
      Specification: 0,
      form: {
        Article_SerialNumber: "",
        Article_Name: '',
        Brand_SerialNumber: '',
        Category_SerialNumber: '',
        Series_SerialNumber: '',
        Item_SerialNumber: '',
        Size: '',
        Unit_Price: '',
        Picture_URL: '',
        Weight: '',
        Weight_Unit: '',
        Package_Quantity: '',
        SKU_Package_Size: '',
        Carton_Quantity: '',
        App_ID: '',
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        pic: '',
        Release_Type: '0',
        Children: {
          article_pic: [],
          article_barcode: [],
          article_specifications: [
            {
              Article_Specifications_SerialNumber: '',
              Article_SerialNumber: '',
              Net_Content: '',  //净含量
              Unit_Price: '', //零售价
              Packing: '', //装箱数
              PackingSize: '', //装箱尺寸
              OutsidePackingSize: '', //外箱尺寸
              Specifications_Name: '', //规格说明
              Picture_URL: '',   //规格图片
              pic: ''
            }
          ]
        }
      },
      tableData: [],
      loading: false,
      is: true,
      is_xq: true
    }
  },
  mounted() {
    this.getData();
    //主图
    var $ul = this.$el.querySelector('.upload_warp_img1')
    this.sortList = Sortable.create($ul, {
      handle: '.upload_warp_img_div1',
      draggable: ".upload_warp_img_div1",
      animation: 150,
      onUpdate: (event) => {
        var newIndex = event.newIndex,
          oldIndex = event.oldIndex
        $li = $ul.children[newIndex],
          $oldLi = $ul.children[oldIndex]
        // 先删除移动的节点
        $ul.removeChild($li)
        // 再插入移动的节点到原有节点，还原了移动的操作
        if (newIndex > oldIndex) {
          $ul.insertBefore($li, $oldLi)
        } else {
          $ul.insertBefore($li, $oldLi.nextSibling)
        }
        console.log(this.fileList);
        var item = this.fileList[event.oldIndex];
        this.fileList.splice(event.oldIndex, 1);
        this.fileList.splice(event.newIndex, 0, item);
      }
    })
    var $ul2 = this.$el.querySelector('.upload_warp_img')
    console.log($ul2);
    this.sortList = Sortable.create($ul2, {
      handle: '.upload_warp_img_div',
      draggable: ".upload_warp_img_div",
      animation: 150,
      onUpdate: (event) => {
        var newIndex = event.newIndex,
          oldIndex = event.oldIndex
        $li = $ul2.children[newIndex],
          $oldLi = $ul2.children[oldIndex]
        // 先删除移动的节点
        $ul2.removeChild($li)
        // 再插入移动的节点到原有节点，还原了移动的操作
        if (newIndex > oldIndex) {
          $ul2.insertBefore($li, $oldLi)
        } else {
          $ul2.insertBefore($li, $oldLi.nextSibling)
        }
        console.log(this.fileList1);
        var item = this.fileList1[event.oldIndex];
        this.fileList1.splice(event.oldIndex, 1);
        this.fileList1.splice(event.newIndex, 0, item);
      }
    })
  },
  computed:{
    Dealer_Name(){
      return function (id) {
        try {
          let str = this.dealer.filter(item=>item.Dealer_SerialNumber==id)[0].Dealer_Name
          return str
        } catch (error) {
          return id
        }
      }
    },
    Brand_Name(){
      return function (id) {
        try {
          let str = this.brand.filter(item=>item.Brand_SerialNumber==id)[0].Brand_Name
          return str
        } catch (error) {
          return id
        }
      }
    },
    Category_Name(){
      return function (id) {
        try {
          let str = this.category.filter(item=>item.Category_SerialNumber==id)[0].Category_Name
          return str
        } catch (error) {
          return id
        }
      }
    },
    Series_Name(){
      return function (id) {
        try {
          let str = this.series.filter(item=>item.Series_SerialNumber==id)[0].Series_Name
          return str
        } catch (error) {
          return id
        }
      }
    },
    Item_Name(){
      return function (id) {
        try {
          let str = this.item.filter(item=>item.Item_SerialNumber==id)[0].Item_Name
          return str
        } catch (error) {
          return id
        }
      }
    },
    Unit_Name(){
      return function (id) {
        try {
          let str = this.unit.filter(item=>item.Article_Unit_SerialNumber==id)[0].Unit
          return str
        } catch (error) {
          return id
        }
      }
    }
  },
  methods: {
    defaults() {
      this.is = !this.is
    },
    defaults_xi() {
      this.is_xq = !this.is_xq
    },
    getData() {
      let _this = this;
      // 获取品牌
      $.ajax({
        url: DomainName + '/ShopBrand',
        type: 'GET',
        data: { action: "jQueryAjax" },
        success: function (res) {
          res = res.filter(function (item) {
            return item.Row_Status != '1'
          })
          _this.brand = res
          // console.log(res)
          // for (let i = 0; i < res.length; i++) {
          //   _this.brand.push(res[i].Brand_Name);
          // }
        }
      })
      // 查询商品地区
      // $.ajax({
      //   url: DomainName + '/getInquiryAction?token='+ $.cookie('token'),
      //   type: 'POST',
      //   data: { 
      //     Data:'article_province'
      //   },
      //   success: function (res) {
      //     _this.brand = res
      //     // console.log(res)
      //     // for (let i = 0; i < res.length; i++) {
      //     //   _this.brand.push(res[i].Brand_Name);
      //     // }
      //   }
      // })
      // SKU单位
      $.ajax({
        url: DomainName + '/ArticleUnit',
        type: 'GET',
        data: { action: "jQueryAjax" },
        success: function (res) {
          res = res.filter(function (item) {
            return item.Row_Status != '1'
          })
          _this.unit = res
          console.log(_this.unit)
          // for (let i = 0; i < res.length; i++) {
          //   _this.unit.push(res[i].Unit);
          // }
        }
      })
      // 商品类别
      $.ajax({
        url: DomainName + '/ShopCategory',
        type: 'GET',
        data: { action: "jQueryAjax" },
        success: function (res) {
          res = res.filter(function (item) {
            return item.Row_Status != '1'
          })
          _this.category = res
          console.log(_this.category)
          // for (let i = 0; i < res.length; i++) {
          //   _this.category.push(res[i].Category_Name);
          // }
        }
      })
      //商品系列
      $.ajax({
        url: DomainName + '/ShopSeries',
        type: 'GET',
        data: { action: "jQueryAjax" },
        success: function (res) {
          res = res.filter(function (item) {
            return item.Row_Status != '1'
          })
          _this.series = res
          console.log(_this.series)
          // for (let i = 0; i < res.length; i++) {
          //   _this.series.push(res[i].Series_Name);
          // }
        }
      })
      //商品款型
      $.ajax({
        url: DomainName + '/ShopItem',
        type: 'GET',
        data: { action: "jQueryAjax" },
        success: function (res) {
          res = res.filter(function (item) {
            return item.Row_Status != '1'
          })
          _this.item = res
          console.log(_this.item)
        }
      })
      //经销商
      $.ajax({
        url: DomainName + '/getInquiryAction?token='+$.cookie("token"),
        type: 'POST',
        data: { 
          Data:'dealer_info',
        },
        success: function (res) {
          _this.dealer = res
        }
      })
    },
    // 提交表单
    submitForm(formName) {
      let TypeNum1 = 0;
      let TypeNum2 = 0;
      this.form.Children.article_pic.forEach(item => {
        if (item.Picture_Type == '0') {
          TypeNum1++
          item.Picture_Order = TypeNum1;
        }
        if (item.Picture_Type == '1') {
          TypeNum2++
          item.Picture_Order = TypeNum2;
        }
      }
      )
      let reg = /^\d*\.{0,1}\d{0,1}$/
      let _this = this
      //验证子表数据
      if (!reg.test(this.form.Unit_Price)) {
        return _this.$message.error("吊牌价输入错误")
      }
      //限制只能输入一个小数点
      let a = 0
      for (let i = 0; i < _this.form.Children.article_specifications.length; i++) {
        if (!reg.test(_this.form.Children.article_specifications[i].Unit_Price)) {
          a++
        }
      }
      if (a != 0) {
        _this.$message.error("零售价输入错误")
        return
      }
      let b = 0
      for (let i = 0; i < _this.form.Children.article_specifications.length; i++) {
        if (_this.form.Children.article_specifications[i].Picture_URL == '') {
          b++
        }
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          _this.loading = true
          _this.form.Article_SerialNumber = _this.form.Article_SerialNumber+"-" + $.cookie('enterprise')
          _this.fileList.forEach(function (item, index) {
            _this.form.Children.article_pic.push({
              article_picNumber: '',
              Article_SerialNumber: '',
              Picture_Order: item.Picture_Order,
              Picture_Type: item.Picture_Type,
              Picture_Url: item.Picture_Url,
            });
          })
          _this.fileList1.forEach(function (item, index) {
            _this.form.Children.article_pic.push({
              article_picNumber: '',
              Article_SerialNumber: '',
              Picture_Order: item.Picture_Order,
              Picture_Type: item.Picture_Type,
              Picture_Url: item.Picture_Url,
            });
          })
          _this.fileList2.forEach(function (item, index) {
            _this.form.Children.article_barcode.push({
              BarCode: '',
              Article_SerialNumber: '',
              Picture_Order: item.Picture_Order,
              Picture_Url: item.Picture_Url,
            });
          })
          _this.form.Children.article_specifications.forEach(item => {
            item.pic = ''
          })
          $.ajax({
            url: DomainName + '/getAddAction?token=' + $.cookie('token'),
            type: 'POST',
            data: {
              Data: JSON.stringify({
                article_info: [_this.form]
              }),
            },
            success: function (res) {
              if (res.Status === 'success') {
                _this.$message.success("操作成功")
                window.history.go(-1);
              } else {
                _this.$message.error("操作失败，请稍后再试")
              }
            },
            error: function () {
              _this.$message.error("操作失败，请稍后再试")
            },
            complete: function (XMLHttpRequest) {
              _this.loading = false
              if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                window.parent.document.location.href = absolutepath()  + XMLHttpRequest.getResponseHeader("CONTENTPATH");
              }
            }
          })
        } else {
          _this.$message.error("请检查商品信息有无漏填")
          return false;
        }

      });
    },
    add_article_specifications() {
      this.form.Children.article_specifications.push({
        Article_Specifications_SerialNumber: '',
        Article_SerialNumber: '',
        Net_Content: '',  //净含量
        Unit_Price: '', //零售价
        Packing: '', //装箱数
        PackingSize: '', //装箱尺寸
        OutsidePackingSize: '', //外箱尺寸
        Specifications_Name: '', //规格说明
        Picture_URL: '',
        pic: ''
      })
    },
    remove_article_specifications() {
      if (this.form.Children.article_specifications.length > 1) {
        this.form.Children.article_specifications.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    handleSpecification(index) {
      this.Specification = index
      console.log(this.Specification);
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    onExcel() {
      this.dialogVisible1 = true
    },
    // 商品规格图片
    Specifications(file) {
      let _this = this
      let num = 1
      if (file.size > 150000 && file.size < 500000) {
        num = 0.4
      } else if (file.size > 500000) {
        num = 0.2
      }
      console.log(file);
      new Compressor(file, {
        quality: num,
        success(file) {
          const formData = new FormData();
          formData.append('file', file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            $.ajax({
              type: 'POST',
              url: DomainName + '/FileList',
              data: {
                Data: e.target.result,
                DataLength: file.size,
                FileName: file.name
              },
              complete: function (XMLHttpRequest) {
                _this.loading = false
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = absolutepath()  + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                }
              },
              success: function (Result) {
                if (Result.Status == "success") {
                  _this.form.Children.article_specifications[_this.Specification].pic = e.target.result
                  _this.form.Children.article_specifications[_this.Specification].Picture_URL = Result.Picture_Url
                  _this.$message.success('上传成功')
                } else {
                  _this.$message.error('上传失败')
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试")
              },
              dataType: "json"
            });
          }
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    //商品封面图片
    uploadFront(file) {
      let _this = this
      let num = 1
      // if (file.size > 150000 && file.size < 500000) {
      //   num = 0.4
      // } else if (file.size > 500000) {
      //   num = 0.2
      // }
      new Compressor(file, {
        quality: num,
        // if(file.size) {
        // }
        success(file) {
          console.log(file.size)
          const formData = new FormData();
          formData.append('file', file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            $.ajax({
              type: 'POST',
              url: DomainName + '/FileList',
              data: {
                Data: e.target.result,
                DataLength: file.size,
                FileName: file.name
              },
              complete: function (XMLHttpRequest) {
                _this.loading = false
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = absolutepath()  + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                }
              },
              success: function (Result) {
                _this.form.pic = e.target.result
                if (Result.Status == "success") {
                  _this.form.Picture_URL = Result.Picture_Url
                  _this.$message.success('上传成功')
                  console.log(Result.Picture_Url);
                } else {
                  _this.$message.error('上传失败')
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试")
              },
              dataType: "json"
            });
          }
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    //商品条码
    uploadBarcode(file) {
      let _this = this
      this.fileList2.push({
        BarCode: '',
        Article_SerialNumber: '',
        Picture_Order: this.fileList.length + 1,
        Picture_Url: '',
        pic: ''
      })
      let num = 1
      if (file.size > 150000 && file.size < 500000) {
        num = 0.4
      } else if (file.size > 500000) {
        num = 0.2
      }
      new Compressor(file, {
        quality: num,
        success(file) {
          const formData = new FormData();
          formData.append('file', file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            _this.fileList2[_this.fileList2.length - 1].pic = e.target.result
            $.ajax({
              type: 'POST',
              url: DomainName + '/FileList',
              data: {
                Data: e.target.result,
                DataLength: file.size,
                FileName: file.name
              },
              complete: function (XMLHttpRequest) {
                _this.loading = false
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = absolutepath()  + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                }
              },
              success: function (Result) {
                if (Result.Status == "success") {
                  _this.fileList2[_this.fileList2.length - 1].Picture_Url = Result.Picture_Url
                  _this.$message.success('上传成功')
                } else {
                  _this.$message.error('上传失败')
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试")
              },
              dataType: "json"
            });
          }
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    //商品主图轮播图片
    uploadBanner(file) {
      let _this = this
      this.fileList.push({
        article_picNumber: '',
        Article_SerialNumber: '',
        Picture_Order: this.fileList.length + 1,
        Picture_Type: '0',
        Picture_Url: '',
        pic: ''
      })
      let num = 1
      if (file.size > 150000 && file.size < 500000) {
        num = 0.4
      } else if (file.size > 500000) {
        num = 0.2
      }
      new Compressor(file, {
        quality: num,
        success(file) {
          const formData = new FormData();
          formData.append('file', file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            $.ajax({
              type: 'POST',
              url: DomainName + '/FileList',
              data: {
                Data: e.target.result,
                DataLength: file.size,
                FileName: file.name
              },
              complete: function (XMLHttpRequest) {
                _this.loading = false
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = absolutepath()  + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                  _this.$message(Result.Picture_Url)
                }
              },
              success: function (Result) {
                _this.fileList[_this.fileList.length - 1].pic = e.target.result
                if (Result.Status == "success") {
                  _this.fileList[_this.fileList.length - 1].Picture_Url = Result.Picture_Url
                  _this.$message.success('上传成功')
                } else {
                  _this.$message.error('上传失败')
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试")
              },
              dataType: "json"
            });
          }
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    //商品详情图片
    uploadDetails(file) {
      let _this = this
      this.fileList1.push({
        article_picNumber: '',
        Article_SerialNumber: '',
        Picture_Order: this.fileList1.length + 1,
        Picture_Type: '1',
        Picture_Url: '',
        pic: ''
      })
      let num = 1
      if (file.size > 150000 && file.size < 500000) {
        num = 0.4
      } else if (file.size > 500000) {
        num = 0.2
      }
      new Compressor(file, {
        quality: num,
        success(file) {
          const formData = new FormData();
          formData.append('file', file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            $.ajax({
              type: 'POST',
              url: DomainName + '/FileList',
              data: {
                Data: e.target.result,
                DataLength: file.size,
                FileName: file.name
              },
              complete: function (XMLHttpRequest) {
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = XMLHttpRequest.getResponseHeader("CONTENTPATH");
                }
              },
              success: function (Result) {
                _this.fileList1[_this.fileList1.length - 1].pic = e.target.result
                if (Result.Status == "success") {
                  _this.$message.success('上传成功')
                  _this.fileList1[_this.fileList1.length - 1].Picture_Url = Result.Picture_Url
                } else {
                  _this.$message.error('上传失败')
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试")
              },
              dataType: "json"
            });
          }
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    //查看图片
    handlePictureCardPreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file
    },
    //删除图片
    handleRemove(type, index) {
      console.log(type, index);
      if (type === 'front') {
        this.form.pic = ''
      } else if (type === 'banner') {
        this.fileList = this.fileList.filter(function (item) {
          return item.Picture_Order != index
        })
      } else if (type === 'details') {
        this.fileList1 = this.fileList1.filter(function (item) {
          return item.Picture_Order != index
        })
      } else if (type === 'barcode') {
        this.fileList2 = this.fileList2.filter(function (item) {
          return item.Picture_Order != index
        })
      }
      else if (type === 'Specifications') {
        console.log(this.form.Children.article_specifications[0])
        this.form.Children.article_specifications[0].Picture_URL = ''
      }
    },
    beforeRemove(file, fileList) {
      this.fileList.pop()
    },

    uploadXLSX(file) {
      this.fileXlsx.push({
        name: file.name,
        url: file.type
      })
      const _this = this
      let arr = []
      var reader = new FileReader();
      reader.readAsBinaryString(file);
      reader.onload = function (e) {
        var data = e.target.result;
        var wb = XLSX.read(data, {
          type: 'binary' //以二进制的方式读取
        });
        var sheet = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
        var json = XLSX.utils.sheet_to_json(sheet);//利用接口实现转换。
        json.forEach(item => {
          let isDealer = _this.isDealer(item['经销商'])
          let AbnormalChildren = [isDealer.abnormal]
          // if (arr.some(i => i.Article_Name == item['商品名称'])) {
          //   arr.forEach(i => {
          //     if (i.Article_Name == item['商品名称']) {
          //       i.Children.article_specifications.push({
          //         Article_Specifications_SerialNumber: '',
          //         Article_SerialNumber: '',
          //         Net_Content: '',  //净含量
          //         Unit_Price: item['吊牌价'] == '' ? '' : item['吊牌价'], //零售价
          //         Packing: item['SKU数量'], //SKU数量
          //         PackingSize: '', //装箱尺寸
          //         OutsidePackingSize: '', //外箱尺寸
          //         Specifications_Name: item['规格'], //规格说明
          //         Picture_URL: '',   //规格图片
          //         Dealer_SerialNumber:isDealer.Dealer_SerialNumber,
          //         Dealer_Amount:item['一件代发价'],
          //         Dealer_Article_SerialNumber:item['规格编码'],
          //         Abnormal:!AbnormalChildren.some(item => item == false),
          //       })
          //     }
          //   })
          // } else {
            let Brand = _this.isBrand(item['品牌'])
            let Category = _this.isCategory(item['类别'])
            let Series = _this.isSeries(item['系列'])
            let Item = _this.isItem(item['款型'])
            let Unit = _this.isUnit(item['单位'])
            let Abnormal = [Brand.abnormal, Category.abnormal, Series.abnormal, Item.abnormal, Unit.abnormal,isDealer.abnormal]
            let arr1 = []
            let pic = '';
            var reg = RegExp(/;/);
            if (reg.test(item['图片地址'])) {
              item['图片地址'].split(';').forEach(url => {
                if (url.charAt(0) == "M") {//主图
                  let str = url.substr(url.lastIndexOf('.'))
                  let str1 = url.replace(str, '')
                  arr1.push({
                    article_picNumber: '',
                    Article_SerialNumber: item["商品id"]+"-"+$.cookie('enterprise'),
                    Picture_Url: '/' + url,
                    Picture_Order: parseInt(str1.substr(str1.lastIndexOf('_') + 1)),
                    Picture_Type: 0,
                  })
                } else if (url.charAt(0) == "D") {//详情图
                  let str = url.substr(url.lastIndexOf('.'))
                  let str1 = url.replace(str, '')
                  arr1.push({
                    article_picNumber: '',
                    Article_SerialNumber: item["商品id"]+"-"+$.cookie('enterprise'),
                    Picture_Url: '/' + url,
                    Picture_Order: parseInt(str1.substr(str1.lastIndexOf('_') + 1)),
                    Picture_Type: 1,
                  })
                } else if (url.charAt(0) == "C") {//封面图
                  pic = url;
                }
              })
            }
            arr.push({
              Article_SerialNumber: item["商品id"]+"-"+$.cookie('enterprise'),
              Article_Name: item['商品名称'],
              Brand_SerialNumber: Brand.Brand_SerialNumber,
              Category_SerialNumber: Category.Category_SerialNumber,
              Series_SerialNumber: Series.Series_SerialNumber,
              Item_SerialNumber: Item.Item_SerialNumber,
              Size: '',
              Unit_Price: item['吊牌价'],
              Picture_URL: '/' + pic,
              Weight: '',
              Weight_Unit: Unit.Article_Unit_SerialNumber,
              Package_Quantity: '',
              SKU_Package_Size: '',
              Carton_Quantity: '',
              ProvinceNumber:item['省份'],
              Enterprise_Info_SerialNumber: $.cookie("enterprise"),
              Release_Type: '0',
              Abnormal: !Abnormal.some(item => item == false),
              Children: {
                article_pic: arr1,
                article_barcode: [],
                article_specifications: [{
                  Article_Specifications_SerialNumber: '',
                  Article_SerialNumber: item["商品id"]+"-"+$.cookie('enterprise'),
                  Net_Content: item['净含量'],  //净含量
                  Unit_Price: item['吊牌价'] == '' ? '' : item['吊牌价'], //零售价
                  Packing: item['SKU数量'] == '' ? '1' : item['SKU数量'], //装箱数
                  PackingSize: '', //装箱尺寸
                  OutsidePackingSize: '', //外箱尺寸
                  Specifications_Name: item['规格'] == '' ? '' : item['规格'], //规格说明
                  Picture_URL: '',   //规格图片
                  Dealer_SerialNumber:isDealer.Dealer_SerialNumber,
                  Dealer_Amount:item['一件代发价'],
                  Dealer_Article_SerialNumber:item['规格编码'],
                  Abnormal:!AbnormalChildren.some(item => item == false),
                }]
              }
            })
          // }
          
        })
        console.log('共'+arr.length+'个商品');
        console.log(JSON.stringify(arr[0]) );
        _this.tableData = arr
      }
    },
    //导入
    // uploadXLSX(file) {
    //   this.fileXlsx.push({
    //     name: file.name,
    //     url: file.type
    //   })
    //   const _this = this
    //   let arr = []
    //   var reader = new FileReader();
    //   reader.readAsBinaryString(file);
    //   reader.onload = function (e) {
    //     var data = e.target.result;
    //     var wb = XLSX.read(data, {
    //       type: 'binary' //以二进制的方式读取
    //     });
    //     var sheet = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
    //     var json = XLSX.utils.sheet_to_json(sheet);//利用接口实现转换。
    //     json.forEach(item => {
    //       let isDealer = _this.isDealer(item['经销商'])
    //       let AbnormalChildren = [isDealer.abnormal]
    //       if (arr.some(i => i.Article_Name == item['商品名称'])) {
    //         arr.forEach(i => {
    //           if (i.Article_Name == item['商品名称']) {
    //             i.Children.article_specifications.push({
    //               Article_Specifications_SerialNumber: '',
    //               Article_SerialNumber: '',
    //               Net_Content: '',  //净含量
    //               Unit_Price: item['吊牌价'] == '' ? '' : item['吊牌价'], //零售价
    //               Packing: item['SKU数量'], //SKU数量
    //               PackingSize: '', //装箱尺寸
    //               OutsidePackingSize: '', //外箱尺寸
    //               Specifications_Name: item['规格'], //规格说明
    //               Picture_URL: '',   //规格图片
    //               Dealer_SerialNumber:isDealer.Dealer_SerialNumber,
    //               Dealer_Amount:item['一件代发价'],
    //               Dealer_Article_SerialNumber:item['规格编码'],
    //               Abnormal:!AbnormalChildren.some(item => item == false),
    //             })
    //           }
    //         })
    //       } else {
    //         let Brand = _this.isBrand(item['品牌'])
    //         let Category = _this.isCategory(item['类别'])
    //         let Series = _this.isSeries(item['系列'])
    //         let Item = _this.isItem(item['款型'])
    //         let Unit = _this.isUnit(item['单位'])
    //         let Abnormal = [Brand.abnormal, Category.abnormal, Series.abnormal, Item.abnormal, Unit.abnormal,isDealer.abnormal]
    //         let arr1 = []
    //         let pic = '';
    //         var reg = RegExp(/;/);
    //         if (reg.test(item['图片地址'])) {
    //           item['图片地址'].split(';').forEach(url => {
    //             if (url.charAt(0) == "M") {//主图
    //               let str = url.substr(url.lastIndexOf('.'))
    //               let str1 = url.replace(str, '')
    //               arr1.push({
    //                 article_picNumber: '',
    //                 Article_SerialNumber: '',
    //                 Picture_Url: '/' + url,
    //                 Picture_Order: parseInt(str1.substr(str1.lastIndexOf('_') + 1)),
    //                 Picture_Type: 0,
    //               })
    //             } else if (url.charAt(0) == "D") {//详情图
    //               let str = url.substr(url.lastIndexOf('.'))
    //               let str1 = url.replace(str, '')
    //               arr1.push({
    //                 article_picNumber: '',
    //                 Article_SerialNumber: '',
    //                 Picture_Url: '/' + url,
    //                 Picture_Order: parseInt(str1.substr(str1.lastIndexOf('_') + 1)),
    //                 Picture_Type: 1,
    //               })
    //             } else if (url.charAt(0) == "C") {//封面图
    //               pic = url;
    //             }
    //           })
    //         }
    //         arr.push({
    //           Article_SerialNumber: "",
    //           Article_Name: item['商品名称'],
    //           Brand_SerialNumber: Brand.Brand_SerialNumber,
    //           Category_SerialNumber: Category.Category_SerialNumber,
    //           Series_SerialNumber: Series.Series_SerialNumber,
    //           Item_SerialNumber: Item.Item_SerialNumber,
    //           Size: '',
    //           Unit_Price: item['吊牌价'],
    //           Picture_URL: '/' + pic,
    //           Weight: '',
    //           Weight_Unit: Unit.Article_Unit_SerialNumber,
    //           Package_Quantity: '',
    //           SKU_Package_Size: '',
    //           Carton_Quantity: '',
    //           ProvinceNumber:item['省份'],
    //           Enterprise_Info_SerialNumber: $.cookie("enterprise"),
    //           Release_Type: '0',
    //           Abnormal: !Abnormal.some(item => item == false),
    //           Children: {
    //             article_pic: arr1,
    //             article_barcode: [],
    //             article_specifications: [{
    //               Article_Specifications_SerialNumber: '',
    //               Article_SerialNumber: '',
    //               Net_Content: item['净含量'],  //净含量
    //               Unit_Price: item['吊牌价'] == '' ? '' : item['吊牌价'], //零售价
    //               Packing: item['SKU数量'] == '' ? '1' : item['SKU数量'], //装箱数
    //               PackingSize: '', //装箱尺寸
    //               OutsidePackingSize: '', //外箱尺寸
    //               Specifications_Name: item['规格'] == '' ? '' : item['规格'], //规格说明
    //               Picture_URL: '',   //规格图片
    //               Dealer_SerialNumber:isDealer.Dealer_SerialNumber,
    //               Dealer_Amount:item['一件代发价'],
    //               Dealer_Article_SerialNumber:item['规格编码'],
    //               Abnormal:!AbnormalChildren.some(item => item == false),
    //             }]
    //           }
    //         })
    //       }
    //     })
    //     console.log('共'+arr.length+'个商品');
    //     console.log(JSON.stringify(arr[0]) );
    //     _this.tableData = arr
    //   }
    // },
    isBrand(str) {
      if (this.brand.some(item => item.Brand_Name == str)) {
        return { Brand_SerialNumber: this.brand.filter(item => item.Brand_Name == str)[0].Brand_SerialNumber, abnormal: true }
      } else {
        return { Brand_SerialNumber: '异常数据(' + (str?str:'') + ')', abnormal: false }
      }
    },
    isCategory(str) {
      if (this.category.some(item => item.Category_Name == str)) {
        return { Category_SerialNumber: this.category.filter(item => item.Category_Name == str)[0].Category_SerialNumber, abnormal: true }
      } else {
        return { Category_SerialNumber: '异常数据(' + (str?str:'') + ')', abnormal: false }
      }
    },
    isSeries(str) {
      if (this.series.some(item => item.Series_Name == str)) {
        return { Series_SerialNumber: this.series.filter(item => item.Series_Name == str)[0].Series_SerialNumber, abnormal: true }
      } else {
        return { Series_SerialNumber: '异常数据(' + (str?str:'') + ')', abnormal: false }
      }
    },
    isItem(str) {
      if (this.item.some(item => item.Item_Name == str)) {
        return { Item_SerialNumber: this.item.filter(item => item.Item_Name == str)[0].Item_SerialNumber, abnormal: true }
      } else {
        return { Item_SerialNumber: '异常数据(' + (str?str:'') + ')', abnormal: false }
      }
    },
    isUnit(str) {
      if (this.unit.some(item => item.Unit == str)) {
        return { Article_Unit_SerialNumber: this.unit.filter(item => item.Unit == str)[0].Article_Unit_SerialNumber, abnormal: true }
      } else {
        return { Article_Unit_SerialNumber: '异常数据(' + (str?str:'') + ')', abnormal: false }
      }
    },
    isDealer(str){
      if (this.dealer.some(item => item.Dealer_Name == str)) {
        return { Dealer_SerialNumber: this.dealer.filter(item => item.Dealer_Name == str)[0].Dealer_SerialNumber, abnormal: true }
      } else {
        return { Dealer_SerialNumber: '', abnormal: false }
      }
    },
    XlsxbeforeRemove() {
      this.fileXlsx.pop()
      this.tableData = []
    },
    getAddAction(data) {
      const _this = this;
      $.ajax({
        type: 'POST',
        url: DomainName + '/getBatchAddAction?token=' + $.cookie('token'),
        data: {
          tableName: 'article_info',
          Data: JSON.stringify(data)
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath()  + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        success: function (Result) {
          if (Result.Status == 'success') {
            _this.$message.success('提交成功')
            window.location.href = './Goods.html'
          }else {
            console.log(Result);
            _this.$message.error('提交失败，有重复商品')
          }
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        dataType: "json"
      });
    },
    submitForm1() {
      // if (!this.tableData.some(item => item.Abnormal == false)) {
        if (!this.loading) {
          this.loading = true
          this.getAddAction(this.tableData)
        }
      // } else {
      //   this.$message.error('存在异常数据')
      // }
    },
    Filter(i) {
      if (i == 1) {
        this.tableData.forEach(item => {
          if (!item.Abnormal) {
            var reg = RegExp(/异常数据/);
            if (reg.test(item.Brand_SerialNumber)) {      
              item.Brand_SerialNumber = ''
            }
            if (reg.test(item.Category_SerialNumber)) {  
              item.Category_SerialNumber = ''
            }
            if (reg.test(item.Item_SerialNumber)) {         
              item.Item_SerialNumber = ''
            }
            if (reg.test(item.Series_SerialNumber)) {        
              item.Series_SerialNumber = ''
            }
            if (reg.test(item.Weight_Unit)) {
              item.Weight_Unit = ''
            }
            item.Abnormal = true
          }
        })
        this.$message.success("异常数据整理完成")
      } else if (i == 2) {
        this.tableData = this.tableData.filter(item => item.Abnormal)
        this.$message.success("已筛选掉异常数据")
      } else if(i == 3){
        // this.loading = true
        let Brand = [];
        let Category = [];
        let Item = [];
        let Series = [];
        let Weight = [];
        this.tableData.forEach(item => {
          if (!item.Abnormal) {
            var reg = RegExp(/异常数据/);
            if (reg.test(item.Brand_SerialNumber)&&this.isSome(Brand,'Brand_Name',item.Brand_SerialNumber.replace("异常数据(", "").replace(")", ""))) {
              Brand.push({Brand_SerialNumber:'',Brand_Name:item.Brand_SerialNumber.replace("异常数据(", "").replace(")", ""),Enterprise_Info_SerialNumber: $.cookie("enterprise")})
            }
            if (reg.test(item.Category_SerialNumber)&&this.isSome(Category,'Category_Name',item.Category_SerialNumber.replace("异常数据(", "").replace(")", ""))) {
              Category.push({Category_SerialNumber:'',Category_Name:item.Category_SerialNumber.replace("异常数据(", "").replace(")", ""),Enterprise_Info_SerialNumber: $.cookie("enterprise")})
            }
            if (reg.test(item.Item_SerialNumber)&&this.isSome(Item,'Item_Name',item.Item_SerialNumber.replace("异常数据(", "").replace(")", ""))) {
              Item.push({Item_SerialNumber:'',Item_Name:item.Item_SerialNumber.replace("异常数据(", "").replace(")", ""),Enterprise_Info_SerialNumber: $.cookie("enterprise")})
            }
            if (reg.test(item.Series_SerialNumber)&&this.isSome(Series,'Series_Name',item.Series_SerialNumber.replace("异常数据(", "").replace(")", ""))) {
              Series.push({Series_SerialNumber:'',Series_Name:item.Series_SerialNumber.replace("异常数据(", "").replace(")", ""),Enterprise_Info_SerialNumber: $.cookie("enterprise")})
            }
            if (reg.test(item.Weight_Unit)&&this.isSome(Weight,'Unit',item.Weight_Unit.replace("异常数据(", "").replace(")", ""))) {
              Weight.push({Weight_Unit:'',Unit:item.Weight_Unit.replace("异常数据(", "").replace(")", ""),Enterprise_Info_SerialNumber: $.cookie("enterprise")})
            }
          }
        })
        let _this = this
        $.ajax({
          type: 'POST',
          url: DomainName + '/getAddAction?token=' + $.cookie('token'),
          data: {
            Data: JSON.stringify({brand:Brand.filter(i=>i.Brand_Name!=''),category:Category.filter(i=>i.Category_Name!=''),item:Item.filter(i=>i.Item_Name!=''), series:Series.filter(i=>i.Series_Name!=''), article_unit:Weight.filter(i=>i.Unit!='')})
          },
          complete: function (XMLHttpRequest) {
            _this.loading = false
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href = absolutepath()  + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          },
          success: function (Result) {
            if (Result.Status == 'success') {
              console.log('提交成功');
              _this.$message.success("主数据更新完成")
            }
          },
          error: function () {
            _this.$message.error("操作失败，请稍后再试")
          },
          dataType: "json"
        }); 
      }
    },
    isSome(arr,key,str){
      for(let i = 0; i < arr.length ; i++){
        if(arr[i][key] == str){
          return false
        }
      }
      return true
    },
    tableCellStyle({ row, column, rowIndex, columnIndex }) {
      if (!row.Abnormal) return { backgroundColor: '#E6A23C' }
    },
  }
})